let keydowns = []
let keyDownIgnore = [
    9, // table
]
window.addEventListener('keydown', function(e) {
    if (keyDownIgnore.indexOf(e.keyCode) !== -1) {
        e.preventDefault();
    }
    if (e.keyCode === 17) {
        keydowns = [e.keyCode];
    } else if (e.keyCode === 83) {
        keydowns.push(e.keyCode);
    } else {
        keydowns = [];
    }
    if (keydowns.length >= 2) {
        e.preventDefault();
    }
    return false;
})

$(function() {

    // 创建日志
    var createFile = $('.create-file')
    createFile.on('click', function () {
        let fileName = prompt('请输入文件名')
        if (fileName) {
            console.log(fileName)
            createDirectory(fileName, '', 0, () => {
                getAllPath()
            })
        }
    })
    // 创建文件
    var createDirectory = function (name, pathParentId, type, fn) {
        var userid = ''
       $.post('/workLog/createDirectory', {
            name: name,
            pathParentId: pathParentId,
            userid: userid,
            type: type,
        })
        .then(res => {
            console.log(res);
            fn(res)
        })
    }
    // 删除文件
    var delDirectory = function (uuid) {
        if (uuid) {
            $.post('/workLog/delDirectory', { uuid: uuid })
                .then(res => {
                    console.log(res);
                    getAllPath()
                })
        }
    }

    // 获取文件内容
    var getContext = function() {
        $(this).parent().find('li').attr('class', '')
        $(this).addClass('active')
        $.post('/workLog/readOrWriteFile', {
            uuid: this.data.uuid, type: 'read'
        })
        .then(function(res) {
            if (res.errorCode === 0 ) {
                var name = res.fileInfo.file.name
                $('.content .log-title input').val(name);
                $('.content textarea.text').val(res.fileInfo.text);
            } else {
                console.error(res);
                alert('打开失败: 有可能是文件不存在')
            }
        })
    }

    // 保存文件内容
    var save = function(uuid) {
        if (uuid) {
            var text = $('textarea.text').val()
            $.post('/workLog/readOrWriteFile', {
                uuid: uuid, type: 'write', text
            })
            .then(function(res) {
                if (res.errorCode === 0 ) {
                    console.log('保存成功')
                } else {
                    console.error(res)
                }
            })
        } else {
            console.error('缺少必要参数');
        }
    }


    // 整理出结构
    const pathStructure = function (arr) {
        let structure = []
        let subdirectory = []
        let directorys = arr.reduce((res, item) => {
            if (item.type === 1) {
                res.push(item)
            }
            if (item.path_parent_id === '' && item.type === 0) {
                structure.push(item)
            } else {
                subdirectory.push(item)
            }
            return res
        }, [])
        let directorysMap = {}
        for (let i = 0; i < directorys.length; i++) {
            let d = directorys[i];
            for (let f of subdirectory) {
                if (f.path_parent_id === d.uuid) {
                    if (directorysMap[f.path_parent_id]) {
                        directorysMap[f.path_parent_id].push(f)
                    } else {
                        directorysMap[f.path_parent_id] = [f]
                    }
                }
            }
        }
        return [
            ...directorys.map(d => {
                return {
                    ...d,
                    children: directorysMap[d.uuid]
                }
            }),
            ...structure
        ]
    }
    // 获取目录结构
    var getAllPath = () => {
        $.post('/workLog/logs', { userid: '' })
            .then(res => {
                if (res.errorCode === 0) {
                    $('.path').html('')
                    let directorys = pathStructure(res.result.results);
                    for (let d of directorys) {
                        let li = document.createElement('li');
                        li.innerHTML = d.name;
                        var span = document.createElement('span')
                        span.innerHTML='删除';
                        span.data = d
                        span.onclick = function(e) {
                            console.log(this.data)
                            if (confirm('是否要删除')) {
                                delDirectory(this.data.uuid)
                            }
                            e.stopPropagation();
                            return false;
                        }
                        li.appendChild(span)
                        li.title = d.name;
                        li.data = d;
                        li.onclick = getContext;
                        $('.path').append(li);
                    }
                    $('.path li:nth(0)').trigger('click');
                    $('.path li:nth(0)').addClass('active');
                } else {
                    alert('发生错误');
                    console.log(res);
                }
            })
            .catch(err => {
                alert('发生错误')
                console.log(err)
            })
    }
    getAllPath()
    // 绑定保存事件
    // 每10秒自动保存一次
    // Ctrl + S 保存 -> 绘制提醒面板
    var getCurrentFile = function() {
        let file = $('.path li.active')[0].data;
        return file;
    }
    const keyboardSave = function(e) {
        if (e.keyCode === 17) {
            keydowns = [e.keyCode];
        } else if (e.keyCode === 83) {
            keydowns.push(e.keyCode);
        } else {
            keydowns = [];
        }
        if (keydowns.length >= 2) {
            console.log('保存一次')
            let file = getCurrentFile();
            save(file.uuid);
            e.preventDefault();
        }
        return false;
    }
    let autoSaveTimer = null
    var autoSave = function() {
        let time = 10 * 1e3;
        autoSaveTimer = setInterval(function() {
            let file = getCurrentFile();
            save(file.uuid);
        }, time)
    }

    window.addEventListener('keyup', keyboardSave)
    $('textarea.text').on('focus', function() {
        autoSave()
    })
    $('textarea.text').on('blur', function() {
        clearInterval(autoSaveTimer)
    })
})
